Remove Duplicates from Sorted List
Question
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Analysis
- 在头节点前加result用以保存原本的头节点
- 将current指针指到存在重复值的最后一个节点,且在循环过程中,须注意current.next不能为空,因为在循环最后的时候还会挪动current
- 在循环末尾移动pre与current指针
- 在找到最后一个重复点并赋给current之后,需要将pre.next指向它
Code
|
|
Remove Duplicates from Sorted List II
Question
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
Analysis
- 与I不同的是需要删除所有的重复元素,而非只留一个
- 步骤均同I,唯一不同的是当找到最后一个重复元素并赋值给current后,pre.next指向的是current.next,除此之外,在pre.next变动之后无需变动pre,因为pre.next已经指向了current.next
Code
|
|